package logic

import (
	"context"
	"fmt"
	"nove/models/cache"
	"nove/models/mysql"

	"nove/noverpc/internal/svc"
	"nove/noverpc/noverpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetPasswordLogic {
	return &ForgetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetPasswordLogic) ForgetPassword(in *noverpc.ForgetPasswordRequest) (*noverpc.ForgetPasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("用户不存在，无法修改")
	}
	res, _ := cache.RDB.Get(l.ctx, "sendSms"+in.Account).Result()
	if in.SendSms != res {
		return nil, fmt.Errorf("验证码错误，无法修改密码")
	}
	user.Password = in.Password
	mysql.DB.Debug().Updates(&user)

	return &noverpc.ForgetPasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
